package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.mapper.*;
import com.woniu.pojo.*;
import com.woniu.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.vo.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author QiuPeng
 * @since 2022-10-12
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DetailedOrderMapper detailedOrderMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    /**
     *  搜索加分页查询
     * @param orderPageVo
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageResult selectByPageAndLikeSearch(OrderPageVo orderPageVo, Integer currentPage, Integer pageSize) {
        IPage iPage = new Page(currentPage, pageSize);
        Page<Map<String,Object >> page =orderMapper.queryByPage(iPage,orderPageVo);
      return new PageResult(page.getTotal(),page.getRecords());


    }

    @Override
    public List<QueryMemberOrderVo> getByMemberId(String memberId) {
        return orderMapper.getByMemberId(memberId);
    }
    /**
     * 生成订单的结算确认信息
     *
     * @param
     * @return
     */
    @Override
    public ClientGoodsOrderVo GenerateGoodsOrder(SettlementConfirmationOrderVo settlementConfirmationOrderVo, String memberId, double discount) {
        ClientGoodsOrderVo clientGoodsOrderVo = new ClientGoodsOrderVo();

        int addressNum = settlementConfirmationOrderVo.getAddressNum();
        List<Receiver> receiverList= receiverMapper.selectMemberId(memberId);
        // 收货信息
        Receiver receiver = receiverList.get(addressNum);

        String address = receiver.getAddress();
        String name = receiver.getName();
        String tel = receiver.getTel();
        clientGoodsOrderVo.setAddress(address);
        clientGoodsOrderVo.setConsigneeName(name);
        clientGoodsOrderVo.setTel(tel);

        List<GoodsShoppingCartVo>  goodsShoppingCartVoList = new ArrayList<>();

        // 定义每个用户购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + memberId;
        List<String> goodsId = settlementConfirmationOrderVo.getGoodsId();
        for (String id : goodsId) {
            GoodsShoppingCartVo goodsShoppingCartVo = new GoodsShoppingCartVo();
            String goods = (String)stringRedisTemplate.opsForHash().get(shoppingCatKey, id);
            Map<String, Object> value = getValue(goods);
            // 1 获取redis中的数据
            System.err.println(value);
            int goodsNum = Integer.parseInt(value.get("goodsNum").toString());

            String image=  String.valueOf(value.get("image").toString());
            double price = Double.parseDouble(value.get("price").toString());
            BigDecimal bigDecimal = BigDecimal.valueOf(price);
            String goodsName = String.valueOf(value.get("name").toString());
            String goodsId1 = String.valueOf(value.get("goodsId").toString());
            // 将redis缓存设置到goodsShoppingCartVo中
            goodsShoppingCartVo.setGoodsNum(goodsNum);
            goodsShoppingCartVo.setImage(image);
            goodsShoppingCartVo.setName(goodsName);
            goodsShoppingCartVo.setPrice(bigDecimal);
            goodsShoppingCartVo.setGoodsId(goodsId1);
            System.err.println(goodsShoppingCartVo);
            goodsShoppingCartVoList.add(goodsShoppingCartVo);

        }
        double totalMoney = 0.0;
        for (GoodsShoppingCartVo goodsShoppingCartVo : goodsShoppingCartVoList) {

            double price = Double.parseDouble(String.valueOf(goodsShoppingCartVo.getPrice()));
            Integer goodsNum = goodsShoppingCartVo.getGoodsNum();
            totalMoney += (price * goodsNum);
        }

        clientGoodsOrderVo.setGoodsShoppingCartVoList(goodsShoppingCartVoList);
        // 优惠的钱之后的价格
          double d = totalMoney  - (totalMoney  * discount);
         double discountMoney =  (double) Math.round(d * 100) / 100;

        BigDecimal bigDecimal = new BigDecimal(totalMoney  * discount).setScale(2, RoundingMode.HALF_UP);

        clientGoodsOrderVo.setTotalMoney(bigDecimal);
        Order order = new Order();
        order.setOrderStatus("0");
        order.setOrderNum(generateUniqueKey());
        order.setIsLogic(0);
        order.setOrderTotalMoney(Double.parseDouble(bigDecimal.toString()));
        int insert = orderMapper.insert(order);
        clientGoodsOrderVo.setOrderId(order.getId());
        clientGoodsOrderVo.setOrderStatus(order.getOrderStatus());
        clientGoodsOrderVo.setPaymentMethod("1");
        clientGoodsOrderVo.setReceiverId(receiver.getId());


        getDetailOrder(clientGoodsOrderVo,memberId,discountMoney);
        return clientGoodsOrderVo;




    }

    public void getDetailOrder(ClientGoodsOrderVo clientGoodsOrderVo, String memberId,Double discountMoney){


        // 订单详细信息
        DetailedOrder detailedOrder = new DetailedOrder();
        // 订单详细信息
        List<GoodsShoppingCartVo> goodsShoppingCartVoList = clientGoodsOrderVo.getGoodsShoppingCartVoList();


        for (GoodsShoppingCartVo goodsShoppingCartVo : goodsShoppingCartVoList) {

            // 获取商品id
            String goodsId = goodsShoppingCartVo.getGoodsId();
            // 订单详细信息
            detailedOrder.setGoodsId(goodsId);

        }
        // 查询出来订单信息
        String orderId = clientGoodsOrderVo.getOrderId();

        // 订单详细信息信息
        detailedOrder.setMemberId(memberId);
        detailedOrder.setOrderId(orderId);
        detailedOrder.setOrderRemarks("0");
        detailedOrder.setPaymentMethod(clientGoodsOrderVo.getPaymentMethod());
        detailedOrder.setReceiverId(clientGoodsOrderVo.getReceiverId());
        detailedOrder.setDiscount(discountMoney);
        detailedOrderMapper.insert(detailedOrder);

        for (GoodsShoppingCartVo goodsShoppingCartVo : goodsShoppingCartVoList) {
            // 商品订单
            GoodsOrder goodsOrder = new GoodsOrder();
            // 商品订单列表

            // 商品id
            goodsOrder.setGoodsId(goodsShoppingCartVo.getGoodsId());
            // 商品价格

            Double price = Double.parseDouble(goodsShoppingCartVo.getPrice().toString()) ;
            goodsOrder.setGoodsTotalPrice(BigDecimal.valueOf(price * goodsShoppingCartVo.getGoodsNum()) );
            // 商品的数量
            goodsOrder.setGoodsNum(goodsShoppingCartVo.getGoodsNum());
            // 订单id
            goodsOrder.setOrderId(orderId);

            System.err.println(BigDecimal.valueOf(price));
            System.err.println(goodsShoppingCartVo.getGoodsId());
            System.err.println(clientGoodsOrderVo.getOrderId());
            goodsOrderMapper.insert(goodsOrder);

        }

    }

    /**
     * 订单支付页面
     *
     * @param clientGoodsOrderVo
     * @return
     */

    @Override
    public PaymentOrderPageVo paymentGoodsOrder(ClientGoodsOrderVo clientGoodsOrderVo, String memberId) {
        // 定义每个用户购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + memberId;
        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
        // 总金额
        double totalMoney = Double.parseDouble(String.valueOf(clientGoodsOrderVo.getTotalMoney()));

        // 订单支付页面
        PaymentOrderPageVo paymentOrderPageVo = new PaymentOrderPageVo();

        // 订单详细信息
        List<GoodsShoppingCartVo> goodsShoppingCartVoList = clientGoodsOrderVo.getGoodsShoppingCartVoList();

        for (GoodsShoppingCartVo goodsShoppingCartVo : goodsShoppingCartVoList) {

            // 获取商品id
            String goodsId = goodsShoppingCartVo.getGoodsId();
            // 清掉购物车里面的信息
            Long delete = hashOperations.delete(shoppingCatKey, goodsId);
            System.out.println(delete);
            // 获取商品的的数量
            Integer goodsNum = goodsShoppingCartVo.getGoodsNum();
            // 通过goodsId查询 该商品在库存中的数量
            Goods goods = goodsMapper.selectById(goodsId);
            // 增加销量
            goods.setBuyNum(goods.getBuyNum() + goodsNum);
            // 减少库存
            goods.setTotal(goods.getTotal() - goodsNum);
            // 把库存设置进去和销量
            goodsMapper.updateById(goods);


        }

        // 查询出来订单信息
        String orderId = clientGoodsOrderVo.getOrderId();

        // 将信息 赋值
        paymentOrderPageVo.setGoodsShoppingCartVoList(clientGoodsOrderVo.getGoodsShoppingCartVoList());

        OrderDetailOrderVo orderDetailOrderVo1 = detailedOrderMapper.selectByOrderId(orderId);
        paymentOrderPageVo.setOrderNum(orderDetailOrderVo1.getOrderNum());
        paymentOrderPageVo.setOrderTime(orderDetailOrderVo1.getOrderTime());
        // 改变 订单状态
        Order order = new Order();
        order.setOrderStatus("1");
        order.setId(orderId);
        orderMapper.updateById(order);


        return  paymentOrderPageVo ;

    }


    /**
     *  string转map
     * @param param
     * @return
     */
    public Map<String, Object> getValue(String param) {
        Map<String, Object> map = new HashMap<>();
        String str = "";
        String key = "";
        Object value = "";
        char[] charList = param.toCharArray();
        boolean valueBegin = false;
        for (int i = 0; i < charList.length; i++) {
            char c = charList[i];
            if (c == '{') {
                if (valueBegin == true) {
                    value = getValue(param.substring(i, param.length()));
                    i = param.indexOf('}', i) + 1;
                    map.put(key, value);
                }
            } else if (c == '=') {
                valueBegin = true;
                key = str;
                str = "";
            } else if (c == ',') {
                valueBegin = false;
                value = str;
                str = "";
                map.put(key, value);
            } else if (c == '}') {
                if (str != "") {
                    value = str;
                }
                map.put(key, value);
                return map;
            } else if (c != ' ') {
                str += c;
            }
        }
        return map;
    }

    /**
     * 生成主键id
     * 时间+随机数
     * @return
     */
    public  synchronized String generateUniqueKey(){
        Random random = new Random();
        // 随机数的量 自由定制，这是9位随机数
        Integer r = random.nextInt(900000000) + 100000000;

        // 返回  13位时间
        Long timeMillis = System.currentTimeMillis();

        // 返回  17位时间
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = sdf.format(new Date());

        // 13位毫秒+9位随机数
        ///return  timeMillis + String.valueOf(r);
        // 17位时间+9位随机数
        return  timeStr + r;
    }

}
